package site.param.util;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;

import java.nio.charset.Charset;
import java.util.Set;

/**
 * Created by Administrator on 2017/1/4.
 */
public enum ZookeeperUtil {

    INSTANCE {
        @Override
        public CuratorFramework getZookeeper() {

            try {
                if (zkTools == null) {
                    zkTools = CuratorFrameworkFactory
                            .builder()
                            .connectString("120.26.198.195:2181")
                            .namespace(zkRootNode)
                            .retryPolicy(new RetryNTimes(10,20000))
                            .sessionTimeoutMs(300000)
                            .build();
                    zkTools.start();
                }
            } catch (Exception e) {
                 e.printStackTrace();
                System.out.println("初始化  失败");
            }

            return zkTools;
        }



        @Override
        public boolean updateNode(String path) {
            try {
                getZookeeper().setData().forPath(path,"".getBytes(Charset.forName("utf-8")));
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }

        @Override
        public boolean createNode(Set<String> sets) {
            try {
                for (String str:sets ){
                    if (getZookeeper().checkExists().forPath(str)==null){
                        getZookeeper().create()//创建一个路径
                                .creatingParentsIfNeeded()//如果指定的节点的父节点不存在，递归创建父节点
                                .withMode(CreateMode.PERSISTENT)//存储类型（临时的还是持久的）
                                .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)//访问权限
                                .forPath(str);//创建的路径
                    }
                    System.out.println("============已经存在的节点");
                }
                return true;
            } catch (Exception e) {
              //  e.printStackTrace();
            }
            return false;
        }

        @Override
        public String zkRootNode() {
          return  zkRootNode;
        }


    };
    private static CuratorFramework zkTools;
    private static final String zkRootNode="paramter";

    public abstract CuratorFramework getZookeeper();

    public abstract boolean updateNode(String path);

    public abstract boolean createNode(Set<String> sets);

    public abstract String zkRootNode();
}
